class VotesController < ApplicationController

  protect_from_forgery :only => [:create, :update, :destroy] 

  def new
    # We expect to get a tag_id, or failing that a tag[tagname] (thank you for the wierd convention, autocomplete! XP)
    tag = Tag.invoke((params[:tag_id] || params[:tag][:tagname]), :create => 'yes')
    
    left     = ImageFact.find(params[:left_id])
    right    = ImageFact.find(params[:right_id])
    plimsoll = ImageFact.find_by_sha1(ImageFact::PLIMSOLL_SHA1)
    btn      = params[:btn]
    search_compare = Tag.invoke params[:search_compare]
    url_suffix = (search_compare.id>0 ? "?search_compare=#{search_compare.id}" : '')


    case btn
      # "invalid" means they pressed enter. Hard to handle properly. I just create tag if needed and redirect back to original voting page.
      when 'invalid': redirect_to "/image_facts/compare/#{tag.id}/#{left.id}/#{right.id}"; return
      when 'PP':
        Vote.balanced left,     plimsoll, tag.tagname, 50
        Vote.balanced right,    plimsoll, tag.tagname, 50
      when 'NP':
        Vote.balanced right,    left,     tag.tagname, 79
        Vote.balanced right,    plimsoll, tag.tagname, 20
        Vote.balanced plimsoll, left,     tag.tagname, 1
      when 'PN':
        Vote.balanced left,     plimsoll, tag.tagname, 20
        Vote.balanced left,     right,    tag.tagname, 79
        Vote.balanced plimsoll, right,    tag.tagname, 1
      when 'NN':
        Vote.balanced plimsoll, left,     tag.tagname, 50
        Vote.balanced plimsoll, right,    tag.tagname, 50
      else raise "unsupported btn value #{btn}"
    end
    
    if(params[:anchor])
      redirect_to "/image_facts/compare/#{tag.id}/#{left.id}/#{right.id}" + url_suffix
    else
      redirect_to "/image_facts/search_compare/#{tag.id}"
    end
  end

end
